//
//  StatusCell.swift
//  新浪微博
//
//  Created by 李赛 on 15/5/20.
//  Copyright (c) 2015年 李赛. All rights reserved.
//

import UIKit
import SDWebImage

// 定义协议
protocol StatusCellDelegate : NSObjectProtocol {
    // 照片视图选中照片
    func statusDidSelectPhoto(cell : StatusCell,pictureCell : PictureCell , photoIndex : Int)
}

class StatusCell: UITableViewCell {

    // 定义协议
    weak var photoDelegate : StatusCellDelegate?
    
    // 用户头像
    @IBOutlet weak var iconView: UIImageView!
    // 用户昵称
    @IBOutlet weak var authorLabel: UILabel!
    // 创建时间
    @IBOutlet weak var createdLabel: UILabel!
    // 来源
    @IBOutlet weak var sourceLabel: UILabel!
    // 微博正文
    @IBOutlet weak var contentLabel: UILabel!
    // 底部视图
    @IBOutlet weak var bottomView: UIView!
    // 认证图标
    @IBOutlet weak var memberIcon: UIImageView!
    // 会员图标
    @IBOutlet weak var vipIcon: UIImageView!
    // 配图视图
    @IBOutlet weak var pictureView: UICollectionView!
    
    
    // 转发微博正文
    @IBOutlet weak var forwardLabel: UILabel!
    
    
    // collection的宽
    @IBOutlet weak var pictureWidth: NSLayoutConstraint!
    // collection的高
    @IBOutlet weak var pictureHeight: NSLayoutConstraint!
    // collection的布局属性
    @IBOutlet weak var pictureLayout: UICollectionViewFlowLayout!
    
    var status : Status? {
        didSet {
            authorLabel.text = status?.user?.name
            createdLabel.text = status?.created_at
            sourceLabel.text = status?.source
            contentLabel.text = status?.text
            
            // 设置头像
            iconView.sd_setImageWithURL(status?.user?.profireUrl)
            // 设置图标
            memberIcon.image = status?.user?.vipImage
            vipIcon.image = status?.user?.memberImage
            
            // 图片情况分析
            let pictureSize = calaImageFrame(status!)
            // 设置collectionView 的大小
            pictureWidth.constant = pictureSize.viewSize.width
            pictureHeight.constant = pictureSize.viewSize.height
            
            // 设置collectionViewCell的size
            pictureLayout.itemSize = pictureSize.itemSize
            
            // 设置转发微博的正文
            forwardLabel?.text = (status?.retweeted_status?.user?.name ?? "") + ":" + (status?.retweeted_status?.text ?? "")
        }
    }
    
    // 设置可重用标示符
    class func cellIndentifier(status : Status) -> String {
        if status.retweeted_status != nil {
            return "ForwardCell"
        }
        return "HomeCell"
    }
    
    // 根据微博数据计算行高
    func rowHeight(status : Status) -> CGFloat {
        // 设置数据
        self.status = status
        // 强制更新布局
        layoutIfNeeded()
        // 返回底部视图的最大高度
        return CGRectGetMaxY(self.bottomView.frame)
    }
    
    /// 正文换行
    override func awakeFromNib() {
        // 原创微博
        contentLabel.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.width - 20
        
        // 如果不是转发微博  就没有转发微博内容
        // 转发微博
        forwardLabel?.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.width - 20
    }
    
    // 图片情况分析
    private func calaImageFrame(status: Status) -> (viewSize : CGSize, itemSize : CGSize){
        let itemSize = CGSizeMake(90, 90)
        let margin : CGFloat = 10
        let rowCount : Int = 3
        
        if status.pictureUrls?.count == 0 {
            println("没有图片")
            return (CGSizeZero,CGSizeZero)
        }
        if status.pictureUrls?.count == 1 {
            println("单图")
            let key = status.pictureUrls![0].absoluteString!
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            let size = scaleSize(image.size)
//            println("单图------\(size)")
            return (size,size)
        }
        if status.pictureUrls?.count == 4 {
            println("四图")
//            println("四图------\(CGSizeMake(itemSize.width * 2 + margin, itemSize.height * 2 + margin))")
            return (CGSizeMake(itemSize.width * 2 + margin, itemSize.height * 2 + margin),itemSize)
        }
        if status.pictureUrls?.count == 9 {
            println("九图")
//            println("九图------\(CGSizeMake(itemSize.width * 3 + margin * 2, itemSize.height * 3 + margin * 2))")
            return (CGSizeMake(itemSize.width * 3 + margin * 2, itemSize.height * 3 + margin * 2),itemSize)
        }
        
        // 计算行数
        println("多图\(status.pictureUrls?.count)")
        let row = CGFloat((status.pictureUrls!.count - 1) / rowCount + 1)
        //        let w = itemSize.width * CGFloat(rowCount) + margin * (rowCount - 1)
        let w = itemSize.width * CGFloat(rowCount) + margin * (CGFloat(rowCount) - 1)
        let h = itemSize.height * row + margin * (row - 1)
        return (CGSizeMake(w, h),itemSize)
    }
    
    // 判断单图模式下  图片的合适尺寸
    private func scaleSize(size : CGSize) -> (CGSize) {
        let maxWidth = UIScreen.mainScreen().bounds.width - 20
        if size.width < maxWidth {
            return size
        }
        
        let h = size.height * maxWidth / size.width
        
        return CGSizeMake(maxWidth, h)
    }
    
}

/// StatusCell 的数据源方法
extension StatusCell : UICollectionViewDataSource,UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return status?.pictureUrls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("PictureCell", forIndexPath: indexPath)  as! PictureCell
        
        var index = indexPath.item
        
        if index > status!.pictureUrls!.count - 1 {
            index = status!.pictureUrls!.count - 1
            println("-------\(status?.text)")
        }
        
        cell.url = status!.pictureUrls![index]
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        println(indexPath.item)
        let pictureCell = collectionView.cellForItemAtIndexPath(indexPath) as? PictureCell
        
        photoDelegate?.statusDidSelectPhoto(self, pictureCell: pictureCell!, photoIndex: indexPath.item)
    }
    
}

class PictureCell: UICollectionViewCell {
    
    @IBOutlet weak var iconView: UIImageView!
    
    var url: NSURL? {
        didSet{
            iconView.sd_setImageWithURL(url)
        }
    }
    
}
